<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-title">角色管理</div>
      <div class="page-actions">
        <el-button
          type="danger"
          :disabled="selectedRoles.length === 0"
          @click="handleBatchDelete"
          v-if="userStore.hasPermission('role.delete')"
        >
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-if="userStore.hasPermission('role.create')"
        >
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </div>
    </div>
    
    <div class="page-content">
      <!-- 搜索表单 -->
      <div class="search-container">
        <div class="search-header">
          <div class="search-title">
            <el-icon class="search-icon"><Search /></el-icon>
            <span>角色筛选</span>
          </div>
        </div>
        
        <div class="search-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="search-item">
                <label class="search-label">角色名称</label>
                <el-autocomplete
                  v-model="queryParams.name"
                  :fetch-suggestions="getRoleSuggestions"
                  placeholder="搜索角色名称、编码或描述"
                  clearable
                  class="search-input"
                  @select="handleSuggestionSelect"
                  @input="handleSearchInput"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                  <template #suffix>
                    <el-button
                      v-if="queryParams.name"
                      link
                      @click="clearSearch"
                      class="clear-btn"
                    >
                      <el-icon><Close /></el-icon>
                    </el-button>
                  </template>
                  <template #default="{ item }">
                    <div class="suggestion-item">
                      <div class="suggestion-icon">
                        <el-icon v-if="item.type === 'name'"><User /></el-icon>
                        <el-icon v-else-if="item.type === 'code'"><Key /></el-icon>
                        <el-icon v-else><Document /></el-icon>
                      </div>
                      <div class="suggestion-content">
                        <div class="suggestion-text">{{ item.value }}</div>
                        <div class="suggestion-desc">{{ item.desc }}</div>
                      </div>
                      <div class="suggestion-type">
                        <el-tag size="small" :type="item.tagType">{{ item.typeLabel }}</el-tag>
                      </div>
                    </div>
                  </template>
                </el-autocomplete>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="search-item">
                <label class="search-label">角色编码</label>
                <el-input
                  v-model="queryParams.code"
                  placeholder="请输入角色编码"
                  clearable
                  class="search-input"
                  prefix-icon="Key"
                />
              </div>
            </el-col>
            <el-col :span="6">
              <div class="search-item">
                <label class="search-label">状态筛选</label>
                <el-select 
                  v-model="queryParams.status" 
                  placeholder="请选择状态" 
                  clearable 
                  class="search-input"
                >
                  <el-option label="全部状态" :value="null" />
                  <el-option label="✅ 启用中" :value="1" />
                  <el-option label="❌ 已禁用" :value="0" />
                </el-select>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="search-actions">
                <el-button type="primary" @click="handleSearch" class="search-btn">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset" class="reset-btn">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </div>
            </el-col>
          </el-row>
          
          <!-- 快速筛选标签 -->
          <div class="quick-filters">
            <div class="filter-section">
              <span class="filter-label">快速筛选:</span>
              <div class="filter-tags">
                <el-tag
                  :type="queryParams.status === 1 ? 'primary' : ''"
                  :effect="queryParams.status === 1 ? 'dark' : 'plain'"
                  class="filter-tag"
                  @click="handleQuickFilter('status', 1)"
                >
                  <el-icon><CircleCheck /></el-icon>
                  启用角色
                </el-tag>
                <el-tag
                  :type="queryParams.status === 0 ? 'danger' : ''"
                  :effect="queryParams.status === 0 ? 'dark' : 'plain'"
                  class="filter-tag"
                  @click="handleQuickFilter('status', 0)"
                >
                  <el-icon><CircleClose /></el-icon>
                  禁用角色
                </el-tag>
              </div>
            </div>
            <div class="search-stats">
              <el-tag type="info" size="small" class="result-stats">
                找到 {{ filteredTotal }} 个结果
              </el-tag>
              <el-button
                v-if="hasActiveFilters"
                size="small"
                text
                @click="clearAllFilters"
                class="clear-all-btn"
              >
                <el-icon><Close /></el-icon>
                清除所有筛选
              </el-button>
            </div>
          </div>
          
          <!-- 搜索历史 -->
          <div v-if="searchHistory.length > 0" class="search-history">
            <div class="history-header">
              <span class="history-label">
                <el-icon><Clock /></el-icon>
                搜索历史
              </span>
              <el-button size="small" text @click="clearSearchHistory" class="clear-history-btn">
                <el-icon><Delete /></el-icon>
                清除历史
              </el-button>
            </div>
            <div class="history-tags">
              <el-tag
                v-for="(item, index) in searchHistory.slice(0, 5)"
                :key="index"
                size="small"
                class="history-tag"
                @click="applyHistorySearch(item)"
                closable
                @close="removeHistoryItem(index)"
              >
                {{ item }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stats-title">
          <el-icon class="stats-icon"><TrendCharts /></el-icon>
          <span>角色统计概览</span>
          <el-tag type="info" size="small" class="update-time">
            最后更新: {{ new Date().toLocaleTimeString() }}
          </el-tag>
        </div>
        
        <div class="stats-cards">
          <el-row :gutter="24">
            <el-col :span="8">
              <div class="stat-card total-card">
                <div class="stat-header">
                  <div class="stat-icon-wrapper total">
                    <el-icon class="stat-icon-large"><User /></el-icon>
                  </div>
                  <div class="stat-trend">
                    <el-icon class="trend-icon up"><Top /></el-icon>
                    <span class="trend-text">+12%</span>
                  </div>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.total }}</div>
                  <div class="stat-label">总角色数</div>
                  <div class="stat-desc">所有角色数量统计</div>
                </div>
                <div class="stat-footer">
                  <el-progress :percentage="100" :show-text="false" :stroke-width="4" color="#667eea" />
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card active-card">
                <div class="stat-header">
                  <div class="stat-icon-wrapper active">
                    <el-icon class="stat-icon-large"><CircleCheck /></el-icon>
                  </div>
                  <div class="stat-trend">
                    <el-icon class="trend-icon up"><Top /></el-icon>
                    <span class="trend-text">+8%</span>
                  </div>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.active }}</div>
                  <div class="stat-label">启用角色</div>
                  <div class="stat-desc">当前可用的活跃角色</div>
                </div>
                <div class="stat-footer">
                  <el-progress 
                    :percentage="Math.round((stats.active / stats.total) * 100)" 
                    :show-text="false" 
                    :stroke-width="4" 
                    color="#10b981" 
                  />
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="stat-card inactive-card">
                <div class="stat-header">
                  <div class="stat-icon-wrapper inactive">
                    <el-icon class="stat-icon-large"><CircleClose /></el-icon>
                  </div>
                  <div class="stat-trend">
                    <el-icon class="trend-icon down"><Bottom /></el-icon>
                    <span class="trend-text">-3%</span>
                  </div>
                </div>
                <div class="stat-content">
                  <div class="stat-number">{{ stats.inactive }}</div>
                  <div class="stat-label">禁用角色</div>
                  <div class="stat-desc">暂时停用的角色</div>
                </div>
                <div class="stat-footer">
                  <el-progress 
                    :percentage="Math.round((stats.inactive / stats.total) * 100)" 
                    :show-text="false" 
                    :stroke-width="4" 
                    color="#f59e0b" 
                  />
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <!-- 表格区域 -->
      <div class="table-section">
        <div class="table-header">
          <div class="table-title">
            <el-icon class="table-icon"><Grid /></el-icon>
            <span>角色列表</span>
            <el-tag type="info" size="small" class="result-count">
              共 {{ total }} 条记录
            </el-tag>
          </div>
          <div class="table-actions">
            <el-tooltip content="刷新数据" placement="top">
              <el-button 
                circle 
                @click="loadRoles"
                :loading="loading"
                class="refresh-btn"
              >
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            <el-tooltip content="列设置" placement="top">
              <el-button circle class="setting-btn">
                <el-icon><Operation /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </div>
        
        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="roleList"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :row-class-name="getRowClassName"
            class="modern-table"
            element-loading-text="正在加载角色数据..."
            element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.05)"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="角色名称" min-width="150">
              <template #default="{ row }">
                <div class="role-name-cell">
                  <div class="role-avatar">
                    <el-icon><User /></el-icon>
                  </div>
                  <div class="role-info">
                    <div class="role-name">
                      <span class="name-text">{{ row.name }}</span>
                    </div>
                    <div class="role-desc">{{ row.description || '暂无描述' }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="code" label="角色编码" min-width="130">
              <template #default="{ row }">
                <div class="code-cell">
                  <el-tag v-if="row.code" type="info" class="code-tag">
                    <el-icon><Key /></el-icon>
                    {{ row.code }}
                  </el-tag>
                  <span v-else class="empty-code-text">-</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <div class="status-cell">
                  <el-tag
                    :type="row.status ? 'success' : 'danger'"
                    class="status-tag"
                    @click="userStore.hasPermission('role.update') ? handleToggleStatus(row) : null"
                    :class="{ 'clickable': userStore.hasPermission('role.update') }"
                  >
                    <el-icon v-if="row.status"><CircleCheck /></el-icon>
                    <el-icon v-else><CircleClose /></el-icon>
                    {{ row.status ? '启用' : '禁用' }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="userCount" label="用户数" width="100" align="center">
              <template #default="{ row }">
                <div class="user-count-cell">
                  <el-tag 
                    :type="row.userCount > 10 ? 'warning' : 'primary'" 
                    size="small"
                    class="count-tag"
                  >
                    <el-icon><User /></el-icon>
                    {{ row.userCount || 0 }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" min-width="180" align="center">
              <template #default="{ row }">
                <div class="time-cell">
                  <el-icon class="time-icon"><Calendar /></el-icon>
                  <div class="time-content">
                    <div class="date">{{ formatDate(row.createdAt).split(' ')[0] }}</div>
                    <div class="time">{{ formatDate(row.createdAt).split(' ')[1] }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="300" fixed="right" align="center">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      type="primary"
                      size="small"
                      circle
                      @click="handleView(row)"
                      class="action-btn view-btn"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  
                  <el-tooltip content="权限配置" placement="top">
                    <el-button
                      type="success"
                      size="small"
                      circle
                      @click="handlePermission(row)"
                      v-if="userStore.hasPermission('role.assign')"
                      class="action-btn permission-btn"
                    >
                      <el-icon><Key /></el-icon>
                    </el-button>
                  </el-tooltip>
                  
                  <el-dropdown @command="(command) => handleDropdownCommand(command, row)" class="action-dropdown">
                    <el-button size="small" class="more-btn">
                      更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu class="modern-dropdown">
                        <el-dropdown-item 
                          command="edit"
                          v-if="userStore.hasPermission('role.update')"
                          class="dropdown-item"
                        >
                          <el-icon><Edit /></el-icon>
                          编辑角色
                        </el-dropdown-item>
                        <el-dropdown-item 
                          command="configMenu"
                          v-if="userStore.hasPermission('role.update')"
                          class="dropdown-item"
                        >
                          <el-icon><Menu /></el-icon>
                          配置菜单
                        </el-dropdown-item>
                        <el-dropdown-item 
                          command="delete"
                          v-if="userStore.hasPermission('role.delete')"
                          divided
                          class="dropdown-item danger"
                        >
                          <el-icon><Delete /></el-icon>
                          删除角色
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <!-- 分页区域 -->
      <div class="pagination-section">
        <div class="pagination-info">
          <span class="info-text">
            显示第 {{ (queryParams.page - 1) * queryParams.pageSize + 1 }} - 
            {{ Math.min(queryParams.page * queryParams.pageSize, total) }} 条，
            共 {{ total }} 条数据
          </span>
          <el-tag v-if="selectedRoles.length > 0" type="primary" size="small" class="selection-info">
            已选择 {{ selectedRoles.length }} 项
          </el-tag>
        </div>
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
          class="modern-pagination"
          background
        />
      </div>
    </div>
    
    <!-- 角色表单对话框 -->
    <RoleForm
      v-model:visible="formVisible"
      :role="currentRole"
      @confirm="handleFormConfirm"
    />
    
    <!-- 权限分配对话框 -->
    <PermissionAssignment
      v-model:visible="permissionVisible"
      :role="currentRole"
      @confirm="handlePermissionConfirm"
    />
    
    <!-- 角色详情对话框 -->
    <RoleDetail
      v-model:visible="detailVisible"
      :role="currentRole"
      @edit="handleDetailEdit"
      @edit-permissions="handleDetailEditPermissions"
    />
    
    <!-- 菜单配置对话框 -->
    <MenuConfig
      v-model:visible="menuConfigVisible"
      :role="currentRole"
      @confirm="handleMenuConfigConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Delete, Search, Refresh, User, CircleCheck, CircleClose, Setting,
  View, Key, Edit, ArrowDown, Operation, TrendCharts, Top, Bottom,
  Minus, Grid, Calendar, Close, Document, Clock, Menu
} from '@element-plus/icons-vue'
import { roleApi } from '@/api/role' // 角色相关API
import { useUserStore } from '@/stores/user'
import { formatDate } from '@/utils'
import RoleForm from './RoleForm.vue'
import PermissionAssignment from './PermissionAssignment.vue'
import RoleDetail from './RoleDetail.vue'
import MenuConfig from './MenuConfig.vue'

const userStore = useUserStore()

const loading = ref(false)
// 角色列表数据
const roleList = ref([])
const total = ref(0)
const selectedRoles = ref([])
const formVisible = ref(false)
const permissionVisible = ref(false)
const detailVisible = ref(false)
const menuConfigVisible = ref(false)
const currentRole = ref(null)
const searchHistory = ref([])
const filteredTotal = ref(0)

const queryParams = reactive({
  page: 1,
  pageSize: 10,
  name: '',
  code: '',
  status: null
})

// 统计数据
const stats = computed(() => {
  const total = roleList.value.length
  const active = roleList.value.filter(role => role.status === 1).length
  const inactive = roleList.value.filter(role => role.status === 0).length
  
  return { total, active, inactive }
})

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return queryParams.name ||
         queryParams.code ||
         queryParams.status !== null
})

// 模拟数据
// 已移除模拟数据，全部角色数据将通过API获取

const getRoleSuggestions = (queryString, callback) => {
  const suggestions = [];
  if (!queryString) {
    // 返回搜索历史
    const historySuggestions = searchHistory.value.map(item => ({
      value: item,
      desc: '搜索历史',
      type: 'history',
      typeLabel: '历史',
      tagType: 'info'
    }));
    callback(historySuggestions.slice(0, 5));
    return;
  }
  const query = queryString.toLowerCase();
  // 从当前已加载的角色数据中获取建议
  roleList.value.forEach(role => {
    if (role.name && role.name.toLowerCase().includes(query)) {
      suggestions.push({
        value: role.name,
        desc: `角色名称 - ${role.description}`,
        type: 'name',
        typeLabel: '名称',
        tagType: 'primary'
      });
    }
    if (role.code && role.code.toLowerCase().includes(query)) {
      suggestions.push({
        value: role.code,
        desc: `角色编码 - ${role.name}`,
        type: 'code',
        typeLabel: '编码',
        tagType: 'success'
      });
    }
    if (role.description && role.description.toLowerCase().includes(query)) {
      suggestions.push({
        value: role.description,
        desc: `描述内容 - ${role.name}`,
        type: 'description',
        typeLabel: '描述',
        tagType: 'warning'
      });
    }
  });
  // 去重并限制数量
  const uniqueSuggestions = suggestions.filter((item, index, self) =>
    index === self.findIndex(s => s.value === item.value)
  ).slice(0, 8);
  callback(uniqueSuggestions);
};

// 处理搜索输入
const handleSearchInput = (value) => {
  // 实时搜索（防抖）
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    if (value && value.length > 1) {
      handleSearch()
    }
  }, 500)
}

let searchTimeout = null

// 清除搜索
const clearSearch = () => {
  queryParams.name = ''
  handleSearch()
}

// 快速筛选处理
const handleQuickFilter = (type, value) => {
  if (type === 'status') {
    queryParams.status = queryParams.status === value ? null : value
  }
  handleSearch()
}

// 清除所有筛选
const clearAllFilters = () => {
  queryParams.name = ''
  queryParams.code = ''
  queryParams.status = null
  handleSearch()
}

// 保存搜索历史
const saveSearchHistory = (searchText) => {
  if (searchText && !searchHistory.value.includes(searchText)) {
    searchHistory.value.unshift(searchText)
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10)
    }
    localStorage.setItem('roleSearchHistory', JSON.stringify(searchHistory.value))
  }
}

// 清除搜索历史
const clearSearchHistory = () => {
  searchHistory.value = []
  localStorage.removeItem('roleSearchHistory')
}

// 初始化搜索历史
const initSearchHistory = () => {
  const savedHistory = localStorage.getItem('roleSearchHistory')
  if (savedHistory) {
    try {
      searchHistory.value = JSON.parse(savedHistory)
    } catch (e) {
      searchHistory.value = []
      localStorage.removeItem('roleSearchHistory')
      console.error('解析搜索历史记录失败:', e)
    }
  }
}

// 应用历史搜索
const applyHistorySearch = (searchText) => {
  queryParams.name = searchText
  handleSearch()
}

// 移除历史项
const removeHistoryItem = (index) => {
  searchHistory.value.splice(index, 1)
  localStorage.setItem('roleSearchHistory', JSON.stringify(searchHistory.value))
}

// 加载角色列表（表格数据）
const loadRoles = async () => {
  loading.value = true
  try {
    // 准备筛选参数
    const filters = {
      name: queryParams.name,
      code: queryParams.code,
      status: queryParams.status
    };
    
    // 调用分页API，注意后端pageIndex从0开始，前端从1开始
    const res = await roleApi.getRolesPaged(queryParams.page - 1, queryParams.pageSize, filters)
    console.log('角色分页API返回的原始数据:', res)
    // 适配后端返回结构，res是完整响应：{ code: 200, data: { roles: [...], totalCount: 100 }, isSuccess: true }
    const responseData = res.data || {}
    // 映射字段名：roleName -> name, roleCode -> code
    roleList.value = (responseData.roles || []).map(role => ({
      ...role,
      name: role.roleName || role.name,
      code: role.roleCode || role.code || '', // 确保code为空字符串而非undefined
      // 根据编码判断状态，包含"disabled"的为禁用状态
      status: role.status !== undefined ? role.status : 
              (role.roleCode && role.roleCode.includes('disabled') ? 0 : 1),
      userCount: role.userCount || 0, // 使用后端返回的真实用户数量
      createdAt: role.createdAt || new Date().toISOString() // 默认创建时间，后端暂无此字段
    }))
    total.value = responseData.totalCount || 0
    filteredTotal.value = responseData.totalCount || 0
  } catch (e) {
    console.error('获取角色列表失败:', e)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}


const handleSearch = () => {
  queryParams.page = 1
  
  // 保存搜索历史
  if (queryParams.name) {
    saveSearchHistory(queryParams.name)
  }
  
  loadRoles()
}

const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    pageSize: 10,
    name: '',
    code: '',
    status: null
  })
  
  loadRoles()
}

const handleAdd = () => {
  currentRole.value = null
  formVisible.value = true
}

const handleView = (row) => {
  currentRole.value = { ...row }
  detailVisible.value = true
}

const handleEdit = (row) => {
  currentRole.value = { ...row }
  formVisible.value = true
}

const handleConfigMenu = (row) => {
  currentRole.value = { ...row }
  menuConfigVisible.value = true
}

const handlePermission = (row) => {
  currentRole.value = { ...row }
  permissionVisible.value = true
}

// 角色删除
const handleDelete = async (row) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      `确定要删除角色"${row.roleName || row.name}"吗？删除后不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )

    // 调用删除API
    console.log('删除角色，ID:', row.id)
    const response = await roleApi.deleteRole(row.id)
    console.log('删除角色响应:', response)
    
    ElMessage.success('角色删除成功')
    
    // 重新加载角色列表
    await loadRoles()
    
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      ElMessage.info('已取消删除')
    } else {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败: ' + (error.message || '未知错误'))
    }
  }
}

// 批量删除角色
const handleBatchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`,
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 执行批量删除
    const roleIds = selectedRoles.value.map(role => role.id)
    const promises = roleIds.map(id => roleApi.deleteRole(id))
    await Promise.all(promises)
    
    ElMessage.success(`成功删除 ${selectedRoles.value.length} 个角色`)
    selectedRoles.value = [] // 清空选择
    loadRoles() // 重新加载角色列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除失败:', error)
    }
  }
}

// 角色状态切换
const handleToggleStatus = async (row) => {
  try {
    // 先切换状态值，再提交到API
    row.status = row.status === 1 ? 0 : 1
    await roleApi.toggleRoleStatus(row.id, row.status)
    ElMessage.success(`角色已${row.status ? '启用' : '禁用'}`)
  } catch (e) {
    // 如果API调用失败，恢复状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const handleDropdownCommand = (command, row) => {
  switch (command) {
    case 'edit':
      handleEdit(row)
      break
    case 'configMenu':
      handleConfigMenu(row)
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

const handleFormConfirm = async (formData) => {
  try {
    console.log('表单提交数据:', formData)
    
    if (currentRole.value?.id) {
      // 更新角色
      console.log('更新角色，ID:', currentRole.value.id)
      const response = await roleApi.updateRole(currentRole.value.id, {
        RoleName: formData.name,
        RoleCode: formData.code,
        Description: formData.description
      })
      console.log('更新角色响应:', response)
      ElMessage.success('角色更新成功')
    } else {
      // 创建角色
      console.log('创建新角色')
      const response = await roleApi.createRole({
        RoleName: formData.name,
        RoleCode: formData.code,
        Description: formData.description
      })
      console.log('创建角色响应:', response)
      ElMessage.success('角色创建成功')
    }
    
    formVisible.value = false
    await loadRoles()
  } catch (error) {
    console.error('保存角色失败:', error)
    ElMessage.error('保存角色失败: ' + (error.message || '未知错误'))
  }
}

const handlePermissionConfirm = async (data) => {
  try {
    console.log('权限分配确认:', data)
    
    if (!data || !data.roleId || !data.permissionIds) {
      throw new Error('权限数据不完整')
    }
    
    // 由于后端API不可用，这里我们使用模拟数据处理
    console.log('使用模拟数据处理权限分配');
    console.log('角色ID:', data.roleId);
    console.log('分配的权限:', data.permissionIds);
    
    // 直接假设操作成功
    setTimeout(() => {
      console.log('模拟权限分配操作完成');
    }, 100);
    
    // 关闭权限对话框
    permissionVisible.value = false
    
    // 刷新角色列表
    await loadRoles()
    
    // 如果当前在详情页，也刷新详情
    if (detailVisible.value && currentRole.value) {
      await handleDetail(currentRole.value)
    }
    
    ElMessage.success('权限配置成功')
  } catch (error) {
    console.error('权限分配确认处理失败:', error)
    ElMessage.error('模拟权限分配出错：' + (error.message || '未知错误'))
  }
}

const handleMenuConfigConfirm = async () => {
  try {
    console.log('菜单配置确认')
    
    // 关闭菜单配置对话框
    menuConfigVisible.value = false
    
    // 刷新角色列表
    await loadRoles()
    
    ElMessage.success('菜单配置成功')
  } catch (error) {
    console.error('菜单配置确认处理失败:', error)
    ElMessage.error('菜单配置失败：' + (error.message || '未知错误'))
  }
}

const handleDetailEdit = (role) => {
  currentRole.value = { ...role }
  detailVisible.value = false
  formVisible.value = true
}

const handleDetailEditPermissions = (role) => {
  currentRole.value = { ...role }
  detailVisible.value = false
  permissionVisible.value = true
}

const getRowClassName = ({ row }) => {
  if (row.status === 0) {
    return 'disabled-row'
  }
  return ''
}

// 角色下拉选项（用于下拉选择等场景）
const roleOptions = ref([])
// 加载角色下拉数据
const loadRoleOptions = async () => {
  try {
    // 调用API获取所有角色
    const res = await roleApi.getRoles()
    // 赋值给下拉选项
    roleOptions.value = res.data || []
  } catch (e) {
    ElMessage.error('获取角色列表失败')
  }
}

onMounted(() => {
  loadRoleOptions() // 页面加载时获取角色下拉数据
  // initSearchHistory()
  loadRoles()
})
</script>

<style scoped>
.page-container {
  background: #f8fafc;
  min-height: 100vh;
  padding: 0;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 20"><defs><radialGradient id="a" cx="50%" cy="40%"><stop offset="0%" stop-color="%23ffffff" stop-opacity="0.1"/><stop offset="100%" stop-color="%23ffffff" stop-opacity="0"/></radialGradient></defs><rect width="100" height="20" fill="url(%23a)"/></svg>');
  opacity: 0.3;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  margin: 0;
  position: relative;
  z-index: 1;
}

.page-actions {
  display: flex;
  gap: 12px;
  position: relative;
  z-index: 1;
}

.page-content {
  padding: 24px;
  background: #f8fafc;
}

/* 搜索区域样式 */
.search-container {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.search-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  border-bottom: 1px solid #e2e8f0;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.search-icon {
  color: #667eea;
  font-size: 18px;
}

.toggle-btn {
  color: #667eea;
  font-weight: 500;
}

.search-form {
  padding: 24px;
}

.search-item {
  margin-bottom: 16px;
}

.search-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.search-input {
  width: 100%;
}

.search-actions {
  display: flex;
  align-items: flex-end;
  gap: 12px;
  height: 100%;
  padding-bottom: 16px;
}

.search-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
}

.reset-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 24px;
}

.advanced-search {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.checkbox-group {
  display: flex;
  gap: 16px;
}

.range-input {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-separator {
  color: #6b7280;
  font-size: 14px;
}

/* 搜索建议样式 */
.suggestion-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  gap: 12px;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.suggestion-item:hover {
  background: #f3f4f6;
}

.suggestion-icon {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #e5e7eb;
  color: #6b7280;
  font-size: 12px;
  flex-shrink: 0;
}

.suggestion-content {
  flex: 1;
  min-width: 0;
}

.suggestion-text {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.suggestion-desc {
  font-size: 12px;
  color: #6b7280;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-top: 2px;
}

.suggestion-type {
  flex-shrink: 0;
}

.clear-btn {
  color: #9ca3af;
  padding: 0 4px;
  font-size: 12px;
}

.clear-btn:hover {
  color: #6b7280;
}

/* 快速筛选样式 */
.quick-filters {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
  padding: 16px 0;
  border-top: 1px solid #e5e7eb;
}

.filter-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.filter-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: 1px solid #e5e7eb;
}

.filter-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-stats {
  display: flex;
  align-items: center;
  gap: 12px;
}

.result-stats {
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.clear-all-btn {
  color: #dc2626;
  font-weight: 500;
  padding: 4px 8px;
}

.clear-all-btn:hover {
  background: #fef2f2;
  color: #b91c1c;
}

/* 搜索历史样式 */
.search-history {
  margin-top: 16px;
  padding: 16px 0;
  border-top: 1px solid #e5e7eb;
}

.history-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.history-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.clear-history-btn {
  color: #dc2626;
  font-weight: 500;
  padding: 4px 8px;
  font-size: 12px;
}

.clear-history-btn:hover {
  background: #fef2f2;
  color: #b91c1c;
}

.history-tags {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.history-tag {
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  color: #6b7280;
  font-weight: 500;
  border-radius: 4px;
}

.history-tag:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
  color: #374151;
  transform: translateY(-1px);
}

/* 统计区域样式 */
.stats-section {
  margin-bottom: 24px;
}

.stats-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.stats-icon {
  color: #667eea;
  font-size: 20px;
}

.update-time {
  margin-left: auto;
}

.stats-cards {
  margin-bottom: 8px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: var(--card-accent-color);
}

.stat-card.total-card {
  --card-accent-color: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.active-card {
  --card-accent-color: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.stat-card.inactive-card {
  --card-accent-color: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
}

.stat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.stat-icon-wrapper {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.stat-icon-wrapper.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon-wrapper.active {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
}

.stat-icon-wrapper.inactive {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}

.stat-icon-large {
  font-size: 24px;
  color: white;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 600;
}

.trend-icon.up {
  color: #10b981;
}

.trend-icon.down {
  color: #ef4444;
}

.trend-icon.stable {
  color: #6b7280;
}

.trend-text {
  color: inherit;
}

.stat-content {
  margin-bottom: 16px;
}

.stat-number {
  font-size: 32px;
  font-weight: 800;
  color: #1f2937;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.stat-desc {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.4;
}

.stat-footer {
  margin-top: 16px;
}

/* 表格区域样式 */
.table-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
  overflow: hidden;
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.table-icon {
  color: #667eea;
  font-size: 18px;
}

.result-count {
  margin-left: 8px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.refresh-btn, .setting-btn {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: white;
  color: #6b7280;
  transition: all 0.3s ease;
}

.refresh-btn:hover, .setting-btn:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
  color: #374151;
}

.table-container {
  overflow: hidden;
}

.modern-table {
  border-radius: 0;
}

/* 表格单元格样式 */
.id-tag {
  font-family: 'Monaco', 'Menlo', monospace;
  font-weight: 600;
}

.role-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.role-avatar {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
  flex-shrink: 0;
}

.role-info {
  flex: 1;
  min-width: 0;
}

.role-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.name-text {
  font-weight: 600;
  color: #1f2937;
}

.role-desc {
  font-size: 12px;
  color: #6b7280;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.code-cell {
  display: flex;
  justify-content: center;
}

.code-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-family: 'Monaco', 'Menlo', monospace;
}

.empty-code-text {
  color: #bdbdbd;
  font-style: italic;
  font-size: 16px;
  font-size: 12px;
  font-weight: 600;
  border-radius: 6px;
}

.status-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-tag {
  padding: 6px 10px;
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.status-tag.clickable {
  cursor: pointer;
  transition: all 0.2s;
}

.user-count-cell {
  display: flex;
  justify-content: center;
}

.count-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 600;
  border-radius: 6px;
}

.time-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}

.time-icon {
  color: #6b7280;
  font-size: 16px;
}

.time-content {
  text-align: left;
}

.date {
  font-size: 13px;
  font-weight: 600;
  color: #374151;
  line-height: 1.2;
}

.time {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.2;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.action-btn {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.view-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border: none;
}

.permission-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
}

.more-btn {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  font-weight: 500;
  padding: 8px 12px;
}

.more-btn:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.action-dropdown {
  margin-left: 4px;
}

.modern-dropdown {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
  padding: 4px 0;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  font-size: 14px;
  color: #374151;
  transition: all 0.2s ease;
}

.dropdown-item:hover {
  background: #f3f4f6;
  color: #1f2937;
}

.dropdown-item.danger {
  color: #dc2626;
}

.dropdown-item.danger:hover {
  background: #fef2f2;
  color: #b91c1c;
}

/* 分页区域样式 */
.pagination-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid #e2e8f0;
}

.pagination-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-text {
  font-size: 14px;
  color: #6b7280;
}

.selection-info {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  font-weight: 500;
}

.modern-pagination {
  --el-pagination-button-bg-color: white;
  --el-pagination-hover-color: #667eea;
}

/* 表格行样式 */
:deep(.disabled-row) {
  background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
  opacity: 0.8;
}

:deep(.el-table) {
  --el-table-border-color: #f3f4f6;
  --el-table-bg-color: white;
  --el-table-tr-bg-color: white;
  --el-table-expanded-cell-bg-color: #f8fafc;
}

:deep(.el-table__header) {
  background: #f8fafc;
}

:deep(.el-table th) {
  background: #f8fafc !important;
  color: #374151;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 2px solid #e5e7eb;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f3f4f6;
  font-size: 14px;
}

:deep(.el-table__row:hover > td) {
  background: #f9fafb !important;
}

:deep(.el-table .el-table__cell) {
  padding: 16px 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    padding: 24px 16px;
  }
  
  .page-content {
    padding: 16px;
  }
  
  .search-form .el-row {
    margin: 0;
  }
  
  .search-form .el-col {
    margin-bottom: 16px;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .pagination-section {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  
  .action-buttons {
    flex-wrap: wrap;
    gap: 4px;
  }
  
  .action-btn {
    min-width: auto;
    padding: 6px 8px;
  }
}

/* 加载动画增强 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  margin-top: -40px;
}

:deep(.el-loading-text) {
  color: #667eea;
  font-weight: 500;
}

/* 滚动条美化 */
:deep(.el-table__body-wrapper)::-webkit-scrollbar {
  height: 8px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
}

:deep(.el-table__body-wrapper)::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 输入框样式增强 */
:deep(.search-input .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.search-input .el-input__wrapper:hover) {
  border-color: #cbd5e1;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

:deep(.search-input .el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 选择器样式增强 */
:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

:deep(.el-select-dropdown) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

/* 日期选择器样式 */
:deep(.el-date-editor .el-input__wrapper) {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 复选框样式 */
:deep(.el-checkbox) {
  margin-right: 16px;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #667eea;
  border-color: #667eea;
}

/* 分割线样式 */
:deep(.el-divider) {
  margin: 24px 0;
}

:deep(.el-divider__text) {
  background: white;
  color: #6b7280;
  font-weight: 500;
  padding: 0 16px;
}

/* 进度条样式 */
:deep(.el-progress-bar__outer) {
  border-radius: 4px;
  background: #f3f4f6;
}

:deep(.el-progress-bar__inner) {
  border-radius: 4px;
}

/* 工具提示样式 */
:deep(.el-tooltip__popper) {
  border-radius: 6px;
  font-size: 12px;
  padding: 8px 12px;
}
</style>
